import Vue from 'vue'
import VueRouter from 'vue-router'

const Index = () => import (/* webpackChunkName: 'index' */ '../views/Index.vue')
const Users = () => import (/* webpackChunkName: 'users' */'../views/users/Users.vue')
const Roles = () => import (/* webpackChunkName: 'rights' */'../views/rights/Roles.vue')
const Rights = () => import (/* webpackChunkName: 'rights' */'../views/rights/Rights.vue')
const Categories = () => import (/* webpackChunkName: 'products' */'../views/products/Categories.vue')
const Goods = () => import (/* webpackChunkName: 'products' */'../views/products/Goods.vue')
const Home = () => import (/* webpackChunkName: 'index' */'../views/home/Home.vue')
const Login = () => import (/* webpackChunkName: 'login' */'../views/Login.vue')
const Params = () => import (/* webpackChunkName: 'products' */'../views/products/Params.vue')
const Orders = () => import (/* webpackChunkName: 'orders' */'../views/orders/Orders.vue')
const Reports = () => import (/* webpackChunkName: 'datas' */'../views/datas/reports.vue')
const GoodsAdd = () => import (/* webpackChunkName: 'products' */'../views/products/GoodsAdd.vue')

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/index' },
  { path: '/login', component: Login },
  { path: '/index',
    component: Index,
    children: [
      { path: '/users', component: Users },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Categories },
      { path: '/goods', component: Goods },
      { path: '/rights', component: Rights },
      { path: '', component: Home },
      { path: '/home', component: Home },
      { path: '/params', component: Params },
      { path: '/orders', component: Orders },
      { path: '/reports', component: Reports },
      { path: '/goods-add', component: GoodsAdd }
    ] }

]

const router = new VueRouter({
  routes
})

// 配置全局前置守卫。进行拦截
// 特点: 将来所有的路由在真正被访问, 显示对应的组件之前, 都会先经过全局前置守卫
// 而且, 只有全局前置守卫放行了, 才能看到对应的内容

// to 到哪去
// from 从哪来
// next() 放行, next(路径) 拦截到对应的路由

// 1. 如果是有 token (有票), 放行
// 2. 如果是去登录 (去买票), 放行
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (token || to.path === '/login') {
    next()
  } else {
    next('/login')
  }
})
export default router
